//
//  UIViewExtension.swift
//  Merchant
//
//  Created by 薛永伟 on 2019/5/13.
//  Copyright © 2019 Yuri. All rights reserved.
//

import Foundation

extension UIView {
    
    /// window的安全区(不管当前视图是否在安全区内)
    func windowSafeArea() -> UIEdgeInsets {
        var insets = UIEdgeInsets.init(top: 20, left: 0, bottom: 0, right: 0)
        if #available(iOS 11, *) {
            if self.safeAreaInsets.top > 0 {
                insets = self.safeAreaInsets
            }else{
                if let keywindow = UIApplication.shared.keyWindow{
                    insets = keywindow.safeAreaInsets
                }
            }
        }
        return insets
    }
    
    /// 安全区(iOS 10 earlier available too)
    var safeArea:UIEdgeInsets{
        var insets = UIEdgeInsets.init(top: 20, left: 0, bottom: 0, right: 0)
        if #available(iOS 11, *) {
            if self.safeAreaInsets.top > 0 {
                insets = self.safeAreaInsets
            }
        }
        return insets
    }
}

extension UIView {
    
    /// 安全距离
    ///
    /// - Returns: 找到最大的安全距离
    func safeInsets()->UIEdgeInsets{
        
        var safeArea = UIEdgeInsets.init(top: 20, left: 0, bottom: 0, right: 0)
        if #available(iOS 11, *){
            safeArea = self.safeAreaInsets
            if safeArea.top == 0 ,let winSafe = UIApplication.shared.keyWindow?.safeAreaInsets{
                safeArea = winSafe
            }
            if safeArea.top == 0{
                safeArea.top = 20
            }
        }
        return safeArea
    }
}
